package com.sd.repay.service.impl;

import com.sd.repay.dao.BaseDao;
import com.sd.repay.service.MerTokenService;
import com.sd.repay.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * @author twoman
 * @Description: 商户token信息服务类
 * @date 2017年10月25日
 */
@Service
public class MerTokenServiceImpl implements MerTokenService {

    private static Logger log = LoggerFactory.getLogger(MerTokenServiceImpl.class);

    @Autowired
    private BaseDao baseDao;


    /**
     * 删除卡片token信息
     *
     * @param cardNo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public int deleteTokenByCardNo(String cardNo) throws Exception {

        String sql = " DELETE FROM t_mer_token_info WHERE card_no = ? ";
        return baseDao.execute(sql, cardNo);
    }

    @Override
    public String getTokenByMerAndAcqAndCard(String merNo, String cardNo, String acqCode) throws Exception {

        String sql = " SELECT token FROM t_mer_token_info WHERE merchant_no = ? AND card_no = ? AND acq_code = ? ORDER BY id DESC ";
        Map<String, Object> result = baseDao.findFirst(sql, new Object[]{merNo, cardNo, acqCode});
        return (result == null || result.isEmpty()) ? "" : StringUtil.filterNull(result.get("token"));
    }

    @Override
    public Map<String, Object> getMapByMerAndCardAndAcq(String merNo, String cardNo, String acqCode) throws Exception {

        String sql = " SELECT * FROM t_mer_token_info WHERE merchant_no = ? AND card_no = ? AND acq_code = ? ORDER BY id DESC ";
        return baseDao.findFirst(sql, new Object[]{merNo, cardNo, acqCode});
    }

    @Override
    @Transactional
    public int updateToken(String merNo, String cardNo, String acqCode, String token) throws Exception {

        String sql = " UPDATE t_mer_token_info SET token = ? WHERE merchant_no = ? AND card_no = ? AND acq_code = ? ";
        return baseDao.execute(sql, new Object[]{token, merNo, cardNo, acqCode});
    }

    @Override
    @Transactional
    public int saveTokenInfo(String merNo, String cardNo, String acqCode, String token, String bak1, String bak2) throws Exception {

        String sql = "INSERT INTO t_mer_token_info(merchant_no, acq_code, card_no, token, create_time, bak1, bak2) VALUES(?,?,?,?,?,?,?)";
        return baseDao.execute(sql, new Object[]{merNo, acqCode, cardNo, token, new Date(), bak1, bak2});
    }
}